package general.servlet;

import com.alibaba.fastjson.JSONObject;
import general.mapper.TestMapper;
import general.service.TestService;
import general.servlet.util.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;


/**
 * @desc 描述
 * create on 2018/10/25 by watson
 */
@WebServlet("/testServlet")
public class TestServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置网页响应类型
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        String path = request.getParameter("path");
        if (StringUtils.isNotBlank(path)){
            switch (path){
                case "testPath": this.testPath(request, response);   break;

            }
        }


        //实现具体操作
        PrintWriter out = response.getWriter();

        //返回结果
        JSONObject jsonObject = new JSONObject();

        Map<String, String[]> parameterMap = request.getParameterMap();
        String idStr = request.getParameter("id");
        if (StringUtils.isBlank(idStr)){
            jsonObject.put("code",400);
            jsonObject.put("msg","id参数不能为空");
            out.println(jsonObject);
        } else {
            try {
                Integer id = Integer.parseInt(idStr);

                jsonObject.put("code",200);
                jsonObject.put("msg","OK");
                jsonObject.put("data",TestService.me.getById(id));

                out.println(jsonObject);
            } catch (NumberFormatException e){
                out.println(e.getMessage());
            } catch (Exception e){
                out.println(e.getMessage());
            }
        }
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


    private void testPath(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("testPath");
        PrintWriter out = response.getWriter();
        out.println("testPath");
        out.close();
    }

}
